import useUpdateEffect from 'hooks/use-update-effect';
import { useState, useMemo, useCallback } from 'react';

export interface Options<T> {
    defaultValue?: T;
    defaultValuePropName?: string,
    valuePropName?: string;
    trigger?: string;
}

export interface Props {
    [key: string]: any
}

export default <T>(props: Props = {}, options: Options<T> = {}) => {
    const { 
        defaultValue,
        defaultValuePropName = 'defaultValue',
        valuePropName = 'value',
        trigger = 'onChange'
    } = options

    const value = props[valuePropName]

    const initialValue = useMemo(() => {
        if (valuePropName in props) {
            return value
        }
        if (defaultValuePropName in props) {
            return defaultValue
        }
    }, [])

    const [state, setState] = useState<T | undefined>(initialValue)

    useUpdateEffect(() => {
        if (valuePropName in props) {
            setState(value)
        }
    }, [value])

    const handleSetState = useCallback((v: T | undefined) => {
        if (!(valuePropName in props)) {
            setState(v)
        }
        if (props[trigger]) {
            props[trigger](v)
        }
    }, [props, valuePropName, trigger])

    return [state, handleSetState] as const
}